package parsing;

import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;

import org.xml.sax.*;
import org.xml.sax.helpers.XMLReaderFactory;
import draft.Player;
import draft.Player.Position;
/*
 * 
 */
//import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array;
public class Parser implements ContentHandler {

	/*
	 * Parser takes in an array list
	 * parse(URL) takes in a URL string and parses it
	 */
  int nodeCount;
  public int numNodes;
  ArrayList<Player> names = new ArrayList<Player>();
  
  public Parser(ArrayList<Player> al){
	  this.names = al;
	  numNodes = Integer.MAX_VALUE;
  }

  public void startDocument() throws SAXException
  {
    nodeCount=0;
  }
  
  public void parse(String url){
	    XMLReader parser;
	    try {
	     parser = XMLReaderFactory.createXMLReader();
	    }
	    catch (SAXException e) {
	     System.err.println("createXMLReader failed.");
	     return;
	    }
	    parser.setContentHandler(this);
	    try {
	    	InputStreamReader isr = new InputStreamReader( new URL(url).openStream()
	    	);
	    	InputSource is = new InputSource( isr);
	        parser.parse(is);
	    }
	    catch (Exception e) {
	      System.err.println(e.toString());
	    }
  }

  public void startElement(String namespaceURI, String localName,
   String qualifiedName, Attributes atts) throws SAXException
  {
	  if(localName == "Player"){
		  
		  Player temp = new Player(atts.getValue("Name"), Position.valueOf(atts.getValue("Position")),Integer.parseInt(atts.getValue("OverallRank").trim()));
		  temp.setTeam(atts.getValue("Team"));
		  temp.positionRating = Integer.parseInt(atts.getValue("PositionRank").trim());
		  temp.byeWeek = Integer.parseInt(atts.getValue("ByeWeek").trim());
		  if(names.size() < numNodes){
			  names.add(temp);
		  }
	  }
	  

    nodeCount++;
  }

  public void endDocument() throws SAXException
  {
    System.out.println("Number of nodes: " + nodeCount);
  }
  public void endElement(String namespaceURI, String localName,
		   String qualifiedName) throws SAXException {
	  
	  
  }
  // Do-nothing methods
  public void setDocumentLocator(Locator l) {}
  public void startPrefixMapping(String p, String u)
   throws SAXException {}
  public void endPrefixMapping(String p) throws SAXException {}
  public void skippedEntity(String n) throws SAXException {}
  public void processingInstruction(String t, String d)
   throws SAXException {}
  public void characters(char[] t, int s, int l)
   throws SAXException {}
  public void ignorableWhitespace(char[] t, int s, int l)
   throws SAXException{}

}
